package com.lifesting.front;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
/**
 * 删除行按钮，使用JSF默认的buttonRender，往table发送一个delete事件
 * 
 * @author david
 *
 */
public class DeleteRowsButton extends UICommand {
	public static final String COMPONENT_TYPE = "com.lifesting.delete_btn";
    public static final String COMPONENT_FAMILY = "javax.faces.HtmlCommandButton";
	public DeleteRowsButton() {
		super();
		setValue("删除");
	}

	static boolean wasClicked(FacesContext context, UIComponent component) {
		String clientId = component.getClientId(context);
		Map<String, String> requestParameterMap = context.getExternalContext()
				.getRequestParameterMap();
		if (requestParameterMap.get(clientId) == null) {
			StringBuilder builder = new StringBuilder(clientId);
			String xValue = builder.append(".x").toString();
			builder.setLength(clientId.length());
			String yValue = builder.append(".y").toString();
			return (requestParameterMap.get(xValue) != null && requestParameterMap
					.get(yValue) != null);
		}
		return true;
	}

	@Override
	public void decode(FacesContext context) {
		super.decode(context);
		//
		
		if (wasClicked(context,this)){
			List<String> ids = new ArrayList<String>();
			String table_id = (String) getAttributes().get("tableFor");
			UIComponent findComponent = getParent().findComponent(table_id);
			String table_row_prefix = findComponent.getClientId(context)+".row";
			Map<String, String> map = context.getExternalContext().getRequestParameterMap();
			for (Iterator<String> itt= map.keySet().iterator(); itt.hasNext();)
			{
				String key = itt.next();
				if(key.startsWith(table_row_prefix))
				{
					String id_to_delete = key.substring(table_row_prefix.length()+1);
					ids.add(id_to_delete);
				}
			}
			DeleteEvent event = new DeleteEvent(findComponent);
			event.setIds(ids.toArray(new String[ids.size()]));
			event.setPhaseId(PhaseId.INVOKE_APPLICATION);
			findComponent.queueEvent(event);
		}
	}
}
